package com.yi.mall.seckill.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yi.mall.common.model.seckill.SeckillGoods;
import com.yi.mall.seckill.mapper.SeckillGoodsMapper;
import com.yi.mall.seckill.service.ISeckillGoodsService;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@CacheConfig(cacheNames = "seckill-goods")
public class SeckillGoodsServiceImpl extends ServiceImpl<SeckillGoodsMapper, SeckillGoods> implements ISeckillGoodsService {
    @Cacheable(key = "#activityId",unless = "#result.isEmpty()")
    @Override
    public List<SeckillGoods> listByActivityId(Integer activityId) {
        LambdaQueryChainWrapper<SeckillGoods> wrapper = new LambdaQueryChainWrapper<>(baseMapper);
        List<SeckillGoods> list = wrapper.eq(SeckillGoods::getActivityId, activityId).list();
        return list;
    }

    @CacheEvict(allEntries = true)
    @Override
    public Boolean removeByActivityId(Integer activityId) {
        LambdaUpdateChainWrapper<SeckillGoods> wrapper = new LambdaUpdateChainWrapper<>(baseMapper);
        boolean removed = wrapper.eq(SeckillGoods::getActivityId, activityId).remove();
        return removed;
    }
    @CachePut(key = "#p0.activityId")
    @Override
    public List<SeckillGoods> updateByActivityId(SeckillGoods seckillGoods) {
        LambdaUpdateChainWrapper<SeckillGoods> updateWrapper = new LambdaUpdateChainWrapper<>(baseMapper);
        LambdaQueryChainWrapper<SeckillGoods> queryWrapper = new LambdaQueryChainWrapper<>(baseMapper);
        updateWrapper
                .eq(SeckillGoods::getActivityId, seckillGoods.getActivityId())
                .update(seckillGoods);
        List<SeckillGoods> list = queryWrapper
                .eq(SeckillGoods::getActivityId, seckillGoods.getActivityId())
                .list();
        return list;
    }
}
